const _add = (num1, num2) => {
  let m = 1
  let s1 = 0
  let s2 = 0
  try {
    s1 = num1.toString().split('.')[1].length
  } catch (err) {
  }
  try {
    s2 = num2.toString().split('.')[1].length
  } catch (err) {
  }

  m = Math.pow(10, Math.max(s1, s2))

  return Math.round(num1 * m + num2 * m) / m
}

const _sub = (num1, num2) => {
  let m = 1
  let s1 = 0
  let s2 = 0
  try {
    s1 = num1.toString().split('.')[1].length
  } catch (err) {
  }
  try {
    s2 = num2.toString().split('.')[1].length
  } catch (err) {
  }

  m = Math.pow(10, Math.max(s1, s2))

  return Math.round(num1 * m - num2 * m) / m
}

const _formatCurrency = (number, places, symbol, thousand, decimal) => {
  number = number || 0
  places = !isNaN(places = Math.abs(places)) ? places : 2
  symbol = symbol !== undefined ? symbol : ''  // ￥
  thousand = thousand || ','
  decimal = decimal || '.'
  let negative = number < 0 ? '-' : ''
  let i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + ''
  let j = i.length
  j = j > 3 ? j % 3 : 0
  return symbol + negative + (j ? i.substr(0, j) + thousand : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : '')
}

const _formatRatio = (num) => {
  return (num * 100).toFixed(2)
}
export default {
  // 数学加法
  add (num1, num2) {
    return _add(num1, num2)
  },
  // 数学减法
  sub (num1, num2) {
    return _sub(num1, num2)
  },
  // 格式化金钱，参数：数值，小数位，符号，千位分隔符，小数点符号
  formatCurrency (number, places, symbol, thousand, decimal) {
    return _formatCurrency(number, places, symbol, thousand, decimal)
  },
  formatRatio (num) {
    return _formatRatio(num)
  }
}
